package cn.com.miao.lynx.plugin.push.aop.interceptor;

import cn.com.miao.lynx.plugin.push.annotation.MessagePushSwitch;
import cn.com.miao.lynx.plugin.push.aop.holder.MessagePushContextHolder;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.AopUtils;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.ClassUtils;

import java.lang.reflect.Method;

/**
 * MessagePushSwitchAnnotationInterceptor
 *
 * @title: MessagePushSwitchAnnotationInterceptor
 * @description:
 * @author: dengmiao
 * @create: 2020-01-14 14:18
 **/
public class MessagePushSwitchAnnotationInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        try {
            Class<?> targetClass = (methodInvocation.getThis() != null ? AopUtils.getTargetClass(methodInvocation.getThis()) : null);
            Method specificMethod = ClassUtils.getMostSpecificMethod(methodInvocation.getMethod(), targetClass);
            Method declaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

            MessagePushSwitch messagePushSwitch = declaredMethod.getDeclaredAnnotation(MessagePushSwitch.class);
            // set current thread message push config name
            MessagePushContextHolder.set(messagePushSwitch.value());
            return methodInvocation.proceed();
        } finally {
            // remove current thread use message push config name
            MessagePushContextHolder.remove();
        }
    }
}
